package per.sen.shopping.infrastructure.consul;

import io.smallrye.health.api.AsyncHealthCheck;
import io.smallrye.mutiny.Uni;
import jakarta.enterprise.context.ApplicationScoped;
import org.eclipse.microprofile.config.inject.ConfigProperty;
import org.eclipse.microprofile.health.HealthCheckResponse;
import org.eclipse.microprofile.health.Liveness;

import java.time.Duration;

/**
 * @Descibe: 健康检测:@Liveness应用程序已启动并运行。
 * @Author: LYS
 * @Date: 2024/5/30 10:07
 */

@Liveness
@ApplicationScoped
public class LivenessAsync  implements AsyncHealthCheck {
    @ConfigProperty(name="quarkus.application.name")
    String applicationName;
    @ConfigProperty(name = "database.up", defaultValue = "false")
    private boolean databaseUp;
    @Override
    public Uni<HealthCheckResponse> call() {

        try {
            simulateDatabaseConnectionVerification();
            return Uni.createFrom().item(HealthCheckResponse.up(applicationName))
                    .onItem().delayIt().by(Duration.ofMillis(10));
        } catch (IllegalStateException e) {
            // cannot access the database
            return Uni.createFrom().item(HealthCheckResponse.down(applicationName))
                    .onItem().delayIt().by(Duration.ofMillis(10));
        }



    }


    private void simulateDatabaseConnectionVerification() {
        if (!databaseUp) {
            throw new IllegalStateException("Cannot contact database");
        }
    }
}
